// 引入 mysql 方法
let {conMysql} = require("../mysql");
const {dateTime} = require("../utils/dateTime");
const {encrypted, verifyPwd, createToken,varifyToken} = require("../utils/utils");
const axios = require("axios");
//注册
async function register(req, res) {
    const {user_name, password} = req.body
    //根据用户名查询users表是否存在当前注册用户名
    let sql = `select user_name from users WHERE user_name = '${user_name}'`;

    let resultArr = await conMysql(sql)
    if (resultArr.length > 0) return res.send({
        code: 500,
        data: [],
        msg: "用户名已存在",
    });

    let add_info = {
        user_name,
        //调用encrypted进行密码加密
        password: encrypted(password),
        //状态默认为0
        state: '0',
        //调用dateTime获取当前时间
        create_time: dateTime(),
        menu:[],
        //角色ID默认为1
        r_id: 1
    }


    let add_sql = `insert into users set user_name='${add_info.user_name}',password='${add_info.password}'`

    let add_result = await conMysql(add_sql)

    if (add_result) {
        res.send({
            code: 200,
            data: [],
            msg: "注册成功",
        });
    } else {
        res.send({
            code: 500,
            data: [],
            msg: "服务器错误",
        });
    }


}

//登录
async function login(req, res) {
    const {user_name, password} = req.body
    //根据用户名查询users表是否存在当前注册用户名
    let sql = `select menu,r_id,user_name, password,state from users WHERE user_name = '${user_name}'`;
    const userList = await conMysql(sql)
    if (userList.length == 0) return res.send({
        code: 500,
        data: [],
        msg: "当前用户不存在",
    })
    console.log(userList[0],'userList')
    if (!verifyPwd(password, userList[0].password)) return res.send({
        code: 500,
        data: [],
        msg: "登录密码错误",
    })

    let info = {
        r_id: userList[0].r_id,
        // user_name: userList[0].user_name,
        // state: userList[0].state,
    }
    //生成token
    let token = createToken(info);
    if (token) {
        res.send({
            code: 200,
            data: {
                r_id: userList[0].r_id,
                user_name: userList[0].user_name,
                state: userList[0].state,
                menu:userList[0].menu,
                token: token
            },
            msg: "登录成功",
        })
    }
}

//微信登录
async function wxlogin(req, res) {
    const { nickName,code,avatarUrl } = req.body
    jscode2session_url =  "https://api.weixin.qq.com/sns/jscode2session?appid=wxbeb2c688385c13b4&secret=0904c6b9801c95f5a805f7e8169f04b9&js_code=" +
        code +
        "&grant_type=authorization_code ";
    const j2s_result = await axios.get(jscode2session_url);

    let sql = `select * from wx_user WHERE openid = '${j2s_result.data.openid}'`;
    const userList = await conMysql(sql)

    let token = ""
    //用户不存在，则把该用户信息写入库里面
    if(userList.length == 0){
        // 获取当前时间
        // let curr_time = new Date().getTime();
        let updatesql = `insert into wx_user (openid,session_key,nickName,avatarUrl) values('${j2s_result.data.openid}','${j2s_result.data.session_key}','${nickName}','${avatarUrl}')`;
        await conMysql(updatesql);
    }else{//更新信息
        let curr_time = new Date().getTime()/1000;
        const sql_update=`update wx_user set curr_time='${curr_time}', nickName='${nickName}',avatarUrl='${avatarUrl}' where openid='${j2s_result.data.openid}'`
        await conMysql(sql_update);
    }
    token = createToken(j2s_result.data.openid);
    //生成token
    if (token) {
        res.send({
            code: 200,
            data: {
                token: token
            },
            msg: "成功",
        })
    }
}

//用户信息
async function userInfo(req, res) {
    console.log( req.body.token,' req.body.token')
    const authorization = req.body.token;
    //拿到token 解析角色r_id
    const r_id = await varifyToken(authorization)

    //在users表中 找到该角色
    const sql_r_id = `select * from users where r_id='${r_id}'`;

    let select_result = await conMysql(sql_r_id);
    console.log(select_result,'select_result')
    res.send({
        code: 200,
        data: {
            user_name:select_result[0].user_name,
            r_id:select_result[0].r_id,
        },
        msg: "成功",
    })

}

//修改用户信息
async function updateInfo(req, res) {
    const authorization = req.body.token;
    //拿到token 解析角色r_id
    const r_id = await varifyToken(authorization)
    //在users表中 找到该角色
    const sql_r_id = `select * from users where r_id='${r_id}'`;
    let select_result = await conMysql(sql_r_id);

    const { password,user_name } = req.body;
    //加密用户输入的新密码
    let encrypted_password = encrypted(password)
    //根据角色id 跟新对应的密码
    const sql_updatepassword=`update users set password='${encrypted_password}',user_name='${user_name}' where r_id='${select_result[0].r_id}'`

    await conMysql(sql_updatepassword);

    res.send({
        code: 200,
        data: {},
        msg: "修改成功",
    })
}

//删除用户
async function deleteUser(req, res) {
    const { r_id } = req.body;
    console.log(r_id,'r_id')
    // 根据用户id查询users表是否存在当前用户
    const sql_r_id_search = `explain select r_id,user_name, password,state from users WHERE r_id = '${r_id}'`;
    const userList = await conMysql(sql_r_id_search);
    if(userList.length== 0){
        res.send({
            code: 201,
            data: {},
            msg: "该用户不存在",
        })
        return
    }
    //删除用户
    const sql_r_id_delete = `delete from users WHERE r_id = '${r_id}'`;
    await conMysql(sql_r_id_delete);
    res.send({
        code: 200,
        data: {},
        msg: "删除成功",
    })
}

module.exports = {register, login, userInfo, updateInfo, deleteUser,wxlogin};
